from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from collections import defaultdict
from django.db.models import Count
import copy
import functools
import json
from django.core.paginator import Paginator

# Create your views here.

from categorySetting.models import catrgorys
def update(request):
    err_info = ''
    update_status = True

    user = request.POST.get("user")
    cate = request.POST.get("cate")

    # print(user, cate)
    try:
        catrgorys.objects.filter(user_id=user).update(cate=cate)
    except Exception as e:
        err_info = e.__str__()
        update_status = False

    result_dict = {
        "res": update_status,
        "msg": err_info
    }
    return JsonResponse(result_dict)

def get_settings(request):
    err_info = ''
    code = 200
    items_per_page = request.GET.get("pageSize")
    page_number = request.GET.get("pageNum")
    try:
        record = catrgorys.objects.values('category_name').order_by('category_name')
        cat = catrgorys.objects.values('category_name').annotate(count=Count('category_name')).values('category_name')
    except Exception as e:
        err_info = e.__str__()
        code = 0

    cate_names = []
    for cate in list(cat):
        cate_names.append(cate['category_name'])

    print(cate_names)
    # 分页
    paginator = Paginator(record.values(), items_per_page)
    page = paginator.page(page_number)
    total = paginator.count
    # 不同类分组
    grouped_results = defaultdict(list)
    for item in page:
        category = item['category_name']
        grouped_results[category].append(item)

    data = json.dumps(grouped_results, ensure_ascii=False)
    categorys_name = json.dumps(cate_names, ensure_ascii=False)
    result_dict = {
        "code": code,
        "data": data,
        "total": total,
        "msg": err_info,
        "categoryKey": categorys_name
    }

    return JsonResponse(result_dict)


def get_activated_category(request):
    err_info = ''
    code = 200
    try:
        record = catrgorys.objects.filter(status=True).values("name")
    except Exception as e:
        err_info = e.__str__()
        code = 0

    data = json.dumps(record, ensure_ascii=False) if isinstance(record, dict) else json.dumps(list(record.values("name")), ensure_ascii=False)
    result_dict = {
        "code": code,
        "data": data,
        "msg": err_info
    }
    return JsonResponse(result_dict)

def updata_status(request):
    err_info = ''
    code = 200

    params: dict = json.loads(request.body)
    status = params["status"]
    # 指定id 只改一个
    if 'id' in params:
        item_id = params["id"]
        try:
            catrgorys.objects.filter(id=item_id).update(status=status)
        except Exception as e:
            err_info = e.__str__()
            code = 0
    # 指定类别 改一整类
    elif 'category' in params:
        category = params["category"]
        try:
            catrgorys.objects.filter(category_name=category).update(status=status)
        except Exception as e:
            err_info = e.__str__()
            code = 0
    result_dict = {
        "code": code,
        "msg": err_info
    }
    return JsonResponse(result_dict)

def delete_category(request):
    err_info = ''
    code = 200
    params: dict = json.loads(request.body)
    item_id = params["id"]
    print(item_id)
    try:
        catrgorys.objects.filter(id=item_id).delete()
    except Exception as e:
        err_info = e.__str__()
        code = 0
    result_dict = {
        "code": code,
        "msg": err_info
    }
    return JsonResponse(result_dict)

def add_category(request):
    err_info = ''
    code = 200

    params: dict = json.loads(request.body)
    item_category_name = params["categoryName"]
    item_name = params["name"]
    try:
        catrgorys.objects.create(category_name=item_category_name, name=item_name)
    except Exception as e:
        err_info = e.__str__()
        code = 0

    result_dict = {
        "code": code,
        "msg": err_info
    }
    return JsonResponse(result_dict)

def updata_category(request):
    err_info = ''
    code = 200

    params: dict = json.loads(request.body)
    item_category_name = params["categoryName"]
    item_name = params["name"]
    item_id = params["id"]
    try:
        catrgorys.objects.filter(id=item_id).update(category_name=item_category_name, name=item_name)
    except Exception as e:
        err_info = e.__str__()
        code = 0

    result_dict = {
        "code": code,
        "msg": err_info
    }
    return JsonResponse(result_dict)